import { ElLoading, ElMessage } from 'element-plus'
import { nextTick } from 'vue'

export const getLoadingInstance = (text) => {
  return ElLoading.service({
    fullscreen: true,
    text,
    background: 'rgba(0, 0, 0, 0.7)',
    lock: true
  })
}

export const loadingWrapper = (fn, text, ...args) => {
  const loadingInstance = getLoadingInstance(text)
  try {
    const timerId = setTimeout(async () => {
      await fn.call(null, ...args)
      if (fn.postFn) {
        // console.log(fn.postArgs)
        fn.postFn.call(null, ...fn.postArgs)
      }
      clearTimeout(timerId)
    }, 100)
  } catch (error) {
    if (typeof error === 'string') {
      ElMessage.error(error)
    } else {
      ElMessage.error(error.message)
    }
    // console.log(error)
  } finally {
    loadingInstance.close()
  }
}